package priv.pfz.basedao.lab.performance;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.text.MessageFormat;

/**
 * @author yyjxp
 * 2024/8/4 15:12
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PerformanceTestUtil {
    private long count;
    private long baseCost;

    public static PerformanceTestUtil createTest(long count) {
        PerformanceTestUtil util = new PerformanceTestUtil();
        util.count = count;
        return util;
    }

    public PerformanceTestUtil runBaseTest(String name, Runnable runnable) {
        long cost = run(runnable);
        baseCost = cost;
        String msg = MessageFormat.format("{0}: {1}({2,number,.##%})", name, cost, 1);
        System.out.println(msg);
        return this;
    }

    public PerformanceTestUtil runTest(String name, Runnable runnable) {
        long cost = run(runnable);
        double rate = (double) cost / baseCost;
        String msg = MessageFormat.format("{0}: {1}({2,number,.##%})", name, cost, rate);
        System.out.println(msg);
        return this;
    }

    private long run(Runnable runnable) {
        runnable.run();
        long begin = System.nanoTime();
        for (int i = 0; i < count; i++) {
            runnable.run();
        }
        return (System.nanoTime() - begin) / 1000_000;
    }
}
